package sound;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import model.general.Util;

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

public class LoadMusic implements ILoadMusic {

	private String filename;
	private boolean isLoop;
	private static String SOUND_DIR = "sound/";
	private Player player;
	private URL path;
	private URI uri;
	private File file;
	private FileInputStream fis;
	private Thread thread;

	public LoadMusic(String srcSound, boolean isLoop) {
		super();
		this.filename = srcSound;
		this.isLoop = isLoop;

	}

	@Override
	public void playMusic() {
		thread = new Thread(new Runnable() {

			@Override
			public void run() {
					loadmusic();
			}
		});
		thread.start();
	}

	@Override
	public void stopMusic() {
		thread.stop();
	}

	private void loadmusic() {
		try {
			if (isLoop) {
				while (true) {
					loadfile();
					player.play();
				}
			} else {
				loadfile();
				player.play();
			}
		} catch (JavaLayerException e) {
			e.printStackTrace();
		}
	}

	private void loadfile() {
		try {
			path = this.getClass().getResource(SOUND_DIR + filename);
			uri = path.toURI();
			file = new File(uri);
			fis = new FileInputStream(file);
			player = new Player(fis);

		} catch (JavaLayerException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
